﻿using NB.MGJ.Common;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common.Utility;
using NB.MGJ.Model;
using NB.MGJ.Model.AntiFleeingEntity;
using NB.MGJ.Service;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace NB.MGJ.Web.Controllers
{
    public partial class FleeGoodsController
    {
        /// <summary>
        /// 窜货
        /// </summary>
        /// =======================================================================
        /// 类名：DemoService DemoController的备注：DemoService~1<br/>
        /// =======================================================================<br/>
        /// 更新履历<br/>
        /// 序号          更新日期          责任人           更新内容<br/>
        /// 001           2017/08/28       詹善福           产品入库<br/>
        /// 002           2017/09/04       詹善福           单标入库<br/>
        /// 003           2017/09/08       詹善福           分离单标<br/>
        /// 004           2017/09/11       詹善福           列出整箱<br/>
        /// 005           2017/09/12       詹善福           物流库存统计<br/>
        /// 006           2017/09/13       詹善福           物流防窜货统计<br/>
        /// =======================================================================<br/>

        #region 产品入库

        /// <summary>
        /// 入库
        /// </summary>
        /// <returns></returns>
        public ActionResult ProductStorage()
        {
            return View();
        }
        /// <summary>
        /// 导出EXCEL
        /// </summary>
        /// <returns></returns>
        public ActionResult ExpotExecl(string Ssearch)
        {
            var model = _mservice.GetAllFleeGood(Ssearch);
            var _byte_batch = Excel.Exprot<V_IOWarehouse>(model.ToList().Where(p => p.ViewDel == 0 && p.FormType == 1).ToList(), new string[] { "所属机构", "入库编码", "产品名称", "产品编码", "入库数量", "仓库", "货品仓位", "状态", "操作人", "备注", "操作时间" }, p =>
            {
                return new object[] { 
                    p.EnterpriseName,
					p.FormCode,
					p.ProductName,
					p.ProductCode,
					p.Num,
					p.WarehouseName,
					p.Location,
					p.Status,
					p.CreateLoginName,
					p.Remark,
					p.CreateDate
				};
            }, "FleeGood");
            return File(_byte_batch, "application/octet-stream", string.Format("{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
        }
        /// <summary>
        /// 获取入库任务
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public JsonResult GetWarehousInfo(SearchModel SearchModel, int pageIndex = 1, int pageSize = 15)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.StrCondition = " 1=1 ";
            LogOnUserModel user = LogOnUser;
            var result = _mservice.GetWarehousInfoService(ref pm, user, SearchModel);
            return Json(result);
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public ActionResult InUploadFile(string filePath)
        {
            try
            {
                LogOnUserModel userModel = LogOnUser;
                AntiFleeing_IOWarehouse model = new AntiFleeing_IOWarehouse();
                int result = 0;
                if (filePath != null)  // 如果有文件, 则保存到一个地址
                {
                    //保存数据
                    model.EnterpriseID = userModel.EnterpriseId;
                    model.CreateLoginID = userModel.UserID;
                    model.CreateLoginName = userModel.RealName??userModel.LoginName;
                    model.CreateDate = DateTime.Now;
                   // model.FormCode = "CK" + GetTimestamp(DateTime.Now);
                    model.FormType = 1;
                    model.FilePath = filePath;
                    model.ViewDel = 0;
                    model.ChangeDate = DateTime.Now;
                    model.Type = 1;
                    model = WipeNullHelper.WipeNull<AntiFleeing_IOWarehouse>(model);
                    StreamReader fsRead = new StreamReader(model.FilePath, System.Text.Encoding.Default);
                    string code = fsRead.ReadLine().TrimEnd(',');//读取一行数据
                    code = code.Replace("\t", "");
                    code = code.Replace("\n", "");
                    code = code.Replace("\r", "");
                    code = code.Replace("，", ",");
                    Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);//获取最上级的机构信息
                    if (code.Trim().Substring(0, 4) != ent.Code)
                    {
                        fsRead.Close();
                        return Json(-2);
                    }
                    var list = _mservice.ListGetTable(code);
                    //判断是否冻结
                    if (list[0].Flag != 0)
                    {
                        fsRead.Close();
                        return Json(-4);
                    }
                    //当前码的最小标数量
                    model.DragNum = list.GroupBy(m => m.levv).Select(m => new
                    {
                        lev = m.Key,
                        count = m.Count(),
                    }).OrderBy(m => m.lev).Last().count;
                    code = list[0].Wl_Code;
                    //如果是经销商 则判断厂家是否给他出过库
                    if (LogOnUser.Distributor != 0)
                    {
                        var outInfo = _mservice.GetOutTable(code);
                        if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                        {
                            fsRead.Close();
                            return Json(-3);//您尚未权限操作该码
                        }
                    }
                    var dt = _mservice.GetTable(code);
                    //是否绑定产品 
                    if (dt == null)
                    {
                        fsRead.Close();
                        return Json(-1);
                    }
                    model.ProductID = dt.ProductId.ToString();
                    int n = 0;
                    while (!fsRead.EndOfStream)
                    {
                        fsRead.ReadLine();
                        n++;
                    }
                    fsRead.Close();
                    model.Num = n + 1;
                    model.DragNum = n * model.DragNum;
                    result = _mservice.Add(model);
                }
                return Json(result);
            }
            catch (Exception)
            {
                return Json(0);
            }

        }
  
        /// <summary>
        /// 删除入库记录*/-
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult DelWarehousInfo(int? id)
        {
            AntiFleeing_IOWarehouse del = new AntiFleeing_IOWarehouse();
            del.Id = id;
            del.ViewDel = 1;//删除
            return Json(_mservice.EditStorageServices(del));
        }
        /// <summary>
        /// 入库编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult EditStorage(int? id)
        {
            if (id.HasValue)
            {
                AntiFleeing_IOWarehouse model = _mservice.GetWarehouseModel(id.Value);
                ViewData["WarehouseId"] = SelWarehouseList(int.Parse(model.WarehouseId.ToString()));
                ViewData["ProductID"] = SelProductList(model.ProductID);
                ViewBag.warehouse = model;
                return View();
            }
            return View();
        }
        /// <summary>
        /// 编辑入库信息
        /// </summary>
        /// <param name="IOWarehouse"></param>
        /// <returns></returns>
        public JsonResult EditStorageInfo(AntiFleeing_IOWarehouse IOWarehouse)
        {
            IOWarehouse.ChangeDate = DateTime.Now;
            IOWarehouse.ChangeLoginID = LogOnUser.UserID;
            IOWarehouse.ChangeLoginName = LogOnUser.RealName??LogOnUser.LoginName;
            IOWarehouse.Status = 1;//待导入
            return Json(_mservice.EditStorageServices(IOWarehouse));
        }
        public ActionResult StorageInfo()
        {
            return View();
        }
        #endregion

        #region 填写物流码入库（单标入库）
        public ActionResult LittleCode(string BoxCode)
        {
            BoxCode = BoxCode.Trim();
            BoxCode = BoxCode.Replace("\t", "");
            BoxCode = BoxCode.Replace("\n", "");
            BoxCode = BoxCode.Replace("\r", "");
            BoxCode = BoxCode.Replace("，", ",");
            AntiFleeing_IOWarehouse model = new AntiFleeing_IOWarehouse();
           // model.FormCode = "RK" + GetTimestamp(DateTime.Now);
            string sql = string.Empty;
            AntiFake_Digitcode dt;
            string[] arr = BoxCode.TrimEnd(',').Split(',');
            Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);//获取最上级的机构信息
            model.DragNum = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (string.IsNullOrWhiteSpace(arr[i].Trim()))
                {
                    return Json("{'id':-1,'text':'第" + (i + 1) + "个码后面存在多余的字符！'}");
                }
                if (arr[i].Trim().Substring(0, 4) != ent.Code)
                {
                    return Json("{'id':-1,'text':'第" + (i + 1) + "该码不属于当前企业！'}");
                }
                //获取码分配信息
                var allotInfo = new CodeManage_Allot();
                if (ent.ID != LogOnUser.EnterpriseId)
                {
                    allotInfo = _mservice.CodeAllotInfo(ent.ID, LogOnUser.EnterpriseId, arr[i].Trim().Substring(4, 4));
                    if (allotInfo == null || allotInfo.AllotType == 2) { return Json("{'id':-1,'text':'第" + (i + 1) + "该码不属于当前企业或未分配！'}"); }
                }
                dt = _mservice.GetTable(arr[i]);
                if (dt == null) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码不存在！'}");
                else
                {
                    if (allotInfo.AllotType == 0)//按号段分配
                    {
                        if (dt.ID < allotInfo.StartCode || dt.ID > allotInfo.EndCode)
                        {
                            return Json("{'id':-1,'text':'第" + (i + 1) + "该码不属于当前企业或未分配！'}");
                        }
                    }
                    if (i == 0) model.ProductID = dt.ProductId.ToString();
                    else
                    {
                        if (model.ProductID != dt.ProductId.ToString())
                        {
                            return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码与其他码绑定的产品不同！'}");
                        }
                    }
                }
                var list = _mservice.ListGetTable(arr[i]);
                //判断是否冻结
                if (list[0].Flag != 0) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已冻结！'}");
                var parentCode = list[0].Wl_Code;
                if (parentCode != arr[i]) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码请分离后再操作！'}");
                //当前码的最小标数量
                model.DragNum += list.GroupBy(s => s.levv).Select(s => new
                {
                    lev = s.Key,
                    count = s.Count(),
                }).OrderBy(s => s.lev).Last().count;
                //如果是经销商 则判断厂家是否给他出过库
                if (LogOnUser.Distributor != 0)
                {
                    var outInfo = _mservice.GetOutTable(parentCode);
                    if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                    {
                        return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码您尚未权限操作！'}");
                    }
                    //判断经销商入库信息
                    var inInfo = _mservice.IsInStorage_Dist(parentCode,LogOnUser.Distributor);
                    if (!inInfo) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已入库'}");
                }
                else
                {
                    var outInfo = _mservice.GetOutTable(parentCode);
                    if (outInfo != null) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码您尚未权限操作！'}");
                    bool isHas = _mservice.GetInStorageInfo(parentCode, LogOnUser.EnterpriseId);
                    if (!isHas) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已入库'}");
                   
                }
            }
            model.FilePath = _mservice.WriteTxt(arr, "RK" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");
            model.Type = 2;
            model.EnterpriseID = LogOnUser.EnterpriseId;
            model.CreateLoginID = LogOnUser.UserID;
            model.CreateLoginName = LogOnUser.RealName??LogOnUser.LoginName;
            model.CreateDate = DateTime.Now;
            model.ViewDel = 0;
            model.Num = arr.Length;
            model.Remark = BoxCode;
            model.FormType = 1;
            model.ChangeDate = DateTime.Now;
            model = WipeNullHelper.WipeNull<AntiFleeing_IOWarehouse>(model);
            int id = _mservice.Add(model);
            return Json("{'id':" + id + "}");
        }
        #endregion

        #region 管辖区域市级
        /// <summary>
        /// 管辖区域市级
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public List<SelectListItem> GetDuoXuanShi(string id)
        {
            var result = _hhservice.GetDuoXuanShiService(id);
            return result;
        }
        //public void GetDuoXuanShi(string textid)
        //{

        //    //先把传过来的省份id  转数组  循环
        //    var result = HtmlHelperService.GetDuoXuanShiService();
        //    ViewBag.Ceshishi= result;
        //   // return result;
        //}
        #endregion

        #region 分离单标

        public ActionResult SingleStandard()
        {
            return View();
        }
        public ActionResult SeparationSingle(string code)
        {
            code = code.Trim();
            LogOnUserModel userModel = LogOnUser;
            AntiFleeing_DevanningRecords record = new AntiFleeing_DevanningRecords();
            record.CZCode = code;
            var list=new List<V_ListBox>();
            string result=Check_Out(code,out list);
            if (!string.IsNullOrEmpty(result)) return Json(result);
            if (list[0].Wl_Code != code)
            {
                int i = _mservice.AddRecords(list[0].Wl_Code, code);
                if (i < 0) return Json("分离失败！");
            }
            record.GLCode = list[list.Count-1].ParentCode;
            int id = _mservice.UpdateParentCode(code, "0");
            if (id > 0)
            {
                //添加操作记录
                record.Type = 2;//分离单标
                record.CreateBy = LogOnUser.UserID;
                record.CreateOn = DateTime.Now;
                _mservice.RecordAdd(record);
                return Json("分离成功！");
            }
            else
            {
                return Json("分离失败！");
            }
        }
        #endregion

        #region 列出整箱

        public ActionResult ShowBoxDemo()
        {
            return View();
        }
        public ActionResult FullContainerLoad()
        {
            return View();
        }
        public ActionResult ListBox(string key)
        {
            key = key.Trim();
            //码的表是否存在
           // Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);
           // int TabIsExist = _mservice.CheckTable(key, ent.ID);
            int TabIsExist = _mservice.CheckTable(key, LogOnUser.EnterpriseId);
            if (TabIsExist == 2)
            {
                List<V_ListBox> listZy = _mservice.ListGetTable(key);
                List<AntiFleeing_Tree> listTree = new List<AntiFleeing_Tree>();
                foreach (var item in listZy)
                {
                    AntiFleeing_Tree tree = new AntiFleeing_Tree();
                    tree.name = item.Wl_Code;
                    tree.value = item.ParentCode ?? "0";
                    listTree.Add(tree);
                }
                var trees = DataTree(listTree, null, true);
                return Json(trees, JsonRequestBehavior.AllowGet);
            }
            else if (TabIsExist == 1)
            {
                return Json("1");
            }
            else
                return Json("0");
        }
        // public static  
        public static List<AntiFleeing_Tree> DataTree(List<AntiFleeing_Tree> _list, string code, bool isF = false)
        {
            if (isF)
            {
                var RS = new List<AntiFleeing_Tree>();
                RS = _list.Where(p => p.value == "0").ToList();
                RS.ForEach(P =>
                {
                    P.children = new List<AntiFleeing_Tree>();
                    P.children.AddRange(DataTree(_list, P.name));
                });
                return RS;
            }
            var b = _list.Where(p => p.value == code).ToList();
            if (!string.IsNullOrWhiteSpace(code))
            {
                if (b.Count == 0 || b == null) return new List<AntiFleeing_Tree>();
                b.ForEach(p =>
                {
                    p.children = new List<AntiFleeing_Tree>();
                    p.children.AddRange(DataTree(_list, p.name));
                });
            }
            return b;
        }

        #endregion

        #region 库存统计
        public ActionResult lnventoryStatistics()
        {
            return View();
        }

        public ActionResult lnventoryShowData()
        {
            return View();
        }
        public JsonResult GetStockData(int warehouseId, string SearchKey, int pageIndex = 1, int pageSize = 10)
        {

            var result = new PagedList<StatisticModel>();
                PagerModel pm = new PagerModel();
                pm.Page = pageIndex;
                pm.PageSize = pageSize;
                pm.FldSort = "  w.createDate desc ";
                if (LogOnUser.Distributor != 0)//经销商
                {
                       pm.StrCondition = string.Format(" W.CREATELOGINID in (select ID from sys_user where FIND_IN_SET(distributor,getDiscChild({0})))", LogOnUser.Distributor);
                }
                else
                {
                    if (LogOnUser.EnterpriseId != 1)
                    {
                        if (string.IsNullOrEmpty(LogOnUser.JuniorEnterprise))
                            pm.StrCondition = "  (w.EnterpriseID  in (0))";
                        else
                            pm.StrCondition = "  (w.EnterpriseID in (" + LogOnUser.JuniorEnterprise + "))";
                    }
                    else pm.StrCondition = " 1=1";
                }
                result = _mservice.GetCountDataByProduct(ref pm, SearchKey, warehouseId);
            return Json(result);
        }

        //绑定仓库下拉框 
        public JsonResult GetWarehouseList()
        {
            IEnumerable<SelectListItem> result = _mservice.GetWarehouseService(LogOnUser.UserID).Select(p =>
            {
                return new SelectListItem() { Text = p.WarehouseName, Value = p.ID.ToString() };
            });
            return Json(result);
        }
        #endregion

        #region 防窜货统计
        public ActionResult GetFleeGoodsData(string SearchKey, int pageIndex = 1, int pageSize = 10)
        {
            if (LogOnUser.EnterpriseId != 1)
            {
                bool isExist = _codelog.IsExist("codelog" + LogOnUser.ECode);
                if (!isExist) return Json("");
                PagerModel pm = new PagerModel();
                pm.Page = pageIndex;
                pm.PageSize = pageSize;
                pm.FldSort = "  w.QueryTime desc ";
                pm.StrCondition = " Fw_Code !='' ";
                var result = _mservice.GetFleeGoodsDataServices(ref pm, SearchKey, LogOnUser.ECode);
                return Json(result);
            }
            else return Json("");

        }

        public ActionResult PreventFlee()
        {
            return View();
        }
        #endregion

        /// <summary>
        /// 分离单标公共方法
        /// </summary>
        /// <param name="pCodeMax">最大一级码</param>
        /// <param name="code">本码</param>
        /// <param name="type">操作类型 2 分离单标 4 出库拆箱</param>
        /// <param name="pcode0">直接上级码</param>
        /// <returns></returns>
        public bool CodeInfoImport(string pCodeMax, string code, int type, string pcodeSmall)
        {
            int i = _mservice.AddRecords(pCodeMax, code);
            if (i < 0) return false;
            AntiFleeing_DevanningRecords record = new AntiFleeing_DevanningRecords();
            record.CZCode = code;
            record.GLCode = pcodeSmall;
            int id = _mservice.UpdateParentCode(code, "0");
            if (id > 0)
            {
                //添加操作记录
                record.Type = 4;//4 出库拆箱 2 分离单标
                record.CreateBy = LogOnUser.UserID;
                record.CreateOn = DateTime.Now;
                _mservice.RecordAdd(record);
                return true;
            }
            else
            {
                return false;
            }
        }

    }
}